<template>
    <div class="base-page"  :style="{ height:screenHeight-20+'px'}">
        <!-- <div class="left">
            <select-org @select="onSelectOrg" />
        </div> -->
        <!-- 列表 -->
        <div style="height:100%"  class="right" v-show="viewList === true">
            <div class="e-table">
                <div class="top right-div1">
                    <div class="left">
                        <el-button type="primary" size="mini"
                                @click="setManage"
                                class="btn-greenYellow"
                            >设置管理单位</el-button>
                    </div>
                    <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="输入搜索关键字"
                            v-model="searchKey"
                            @select="onSearch"
                            @change="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                    </div>
                </div>
            </div>
            <div class="e-table" >
                <el-table
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                    :cell-class-name="cellClsNm"
                    @cell-mouse-enter="cellMouseEnter"
                    @cell-mouse-leave="cellMouseLeave"
                    highlight-current-row
                    @select="handleCurrentChange"
                    class="table"
                    ref="tableRef"
                    v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
                >
                    <el-table-column
                        type="selection"
                        width="55">
                    </el-table-column>
                    <el-table-column show-overflow-tooltip fixed label="操作" width="200">
                        <template slot-scope="{ row }">
                            <div class="oparation_box">
                                <i
                                    class="el-icon-edit"
                                    style="font-size: 24px"
                                    :class="{
                                        'icon-edit-active-color': MouseEnterId == row.quataId
                                    }"
                                    @click="tableDbEdit(row)"
                                ></i>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="equipmentNo" label="设备编号" min-width="200" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="equipmentName" label="设备名称" width="200" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="specificationModel" label="规格型号" width="200" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="unit" label="计量单位" width="200" show-overflow-tooltip>
                        <template slot-scope="{ row }">
                            <span>{{ row.unit ? unitMeasure.find(x=>x.value === row.unit).label :'' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="managementUnit" label="管理单位" width="200" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="state" label="状态" width="200" show-overflow-tooltip>
                        <template slot-scope="{ row }">
                            <span>{{ row.state ? equipStatus.find(x=>x.value === row.state).label :'' }}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <Pagination
                :total="paginationInfo.total"
                :pageSize.sync="paginationInfo.pageSize"
                :currentPage.sync="paginationInfo.currentPage"
                @currentChange="getTableData"
                @sizeChange="getTableData"
            />
        </div>
        <!-- 新增编辑界面 -->
        <div class="right" v-if="viewList === 'add' || viewList === 'edit'">
            <div class="e-form" style="padding: 0 10px 10px;">
                <div class="tabs-title">基本信息</div>
                <el-form ref="form" :model="formDataDetail" :rules="rules" label-width="150px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="设备名称：" prop="equipmentName">
                                <span>{{ formDataDetail.equipmentName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="计量单位：">
                                <span>{{ formDataDetail.unit ? unitMeasure.find(x=>x.value === formDataDetail.unit).label :'' }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="规格型号：" prop="specificationModel">
                                <span>{{ formDataDetail.specificationModel }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="设备编号：" prop="equipmentName">
                                <span>{{ formDataDetail.equipmentNo }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="管理单位：" prop="managementUnit">
                                <el-input v-model.number="formDataDetail.managementUnit">
                                    <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="changeEquip(formDataDetail.managementUnitId)"></i>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="设备状态：">
                                <span>{{ formDataDetail.state ? equipStatus.find(x=>x.value === formDataDetail.state).label :'' }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="footer">
                <div class="right-btn">
                    <el-button type="primary" size="mini"
                        @click="onSave"
                    >保存</el-button>
                    <el-button type="default" size="mini"
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import Pagination from '@/components/pagination/pagination'
import { debounce, advanceSearch, showLoading, hideLoading } from '@/utils/common'
import { mapState, mapMutations } from 'vuex'
import { managementUnitList, updateManagementUnit, setManagementUnit } from '@/api/base/equip'
import { isNum } from '@/utils/rules'
import { selectDataClient } from '@/utils/common'
export default {
    components: {
        Pagination,
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            unitMeasure: state => state.equip.equipData.unitMeasure, //计量单位
            equipStatus: state => state.equip.equipData.equipStatus, //设备状态
        }),

        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 300) + 'px'
        },
        // 列表高度
        rightTableHeight () {
            if (this.paginationInfo.total > 0) {
                return this.screenHeight - 170
            } else {
                return this.screenHeight - 118
            }
        },
        // 分配用户、分配岗位列表宽度
        rightTableWidth2 () {
            return (this.screenWidth - 300) + 'px'
        },
        rightTableHeight2 () {
            return this.screenHeight - 210
        }
    },
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            currentRow: [],
            paginationInfo: {
                total: 0,
                pageSize: 20,
                currentPage: 1,
            },
            tableData: [],
            formData: {
                'equipmentName': '',
                'equipmentNo': '',
                'keyword': '',
                'limit': 0,
                'orgId': '',
                'page': 0,
                'specificationModel': '',
                'states': []
            },
            formDataDetail: {},
            MouseEnterId: 0,
            screenWidth: 0,
            screenHeight: 0,
            rules: {
                quantity: [
                    { required: true, message: '请输入数量', trigger: 'blur' },
                    { validator: isNum, trigger: 'blur' },
                ],
                workShiftCount: [
                    { required: true, message: '请输入转换台班数', trigger: 'blur' },
                    { validator: isNum, trigger: 'blur' },
                ],
                equipmentNo: [
                    { required: true, message: '请选择设备编号', trigger: 'blur' },
                ],
            },
            stateList: [
                {
                    label: '停用',
                    value: '1'
                },
                {
                    label: '启用',
                    value: '2'
                },
            ], //设备状态
        }
    },
    mounted () {
        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
        this.getDicValue()
        this.getTableData()
        console.log('unitMeasure', this.unitMeasure)
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setUnitMeasur')//更新计量单位
            this.$store.dispatch('equip/setEquipStatus')//更新设备状态
        },
        async getTableData () {
            showLoading()
            try {
                this.formData.limit = this.paginationInfo.pageSize
                this.formData.page = this.paginationInfo.currentPage
                const resData = await managementUnitList(this.formData)
                this.tableData = resData.list
                this.paginationInfo.total = resData.totalCount
                hideLoading()
            } catch (error) {
                hideLoading()
            }
        },
        onSelectOrg (val) {
            console.log('onSelectOrg: ', { ...val })
            this.paginationInfo.currentPage = 1
            this.formData = {
                ...this.formData,
                ...val,
            }
            this.getTableData()
        },
        addData () {

            this.formDataDetail = {
                'equipmentId': '',
                'equipmentName': '',
                'equipmentNo': '',
                'gmtCreate': '',
                'gmtModified': '',
                'quantity': 0,
                'specificationModel': '',
                'accountId': '',
                'standingBookType': '',
                'state': '2',
                'timeUnit': this.timeUnitList[0].value,
                'workShiftCount': 0,
                'workShiftId': ''
            }
            this.viewList = 'add'

        },
        tableDbEdit (row) {
            this.formDataDetail = row
            console.log('formDataDetail', this.formDataDetail)
            this.viewList = 'edit'
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.quataId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onSearch (e) {
            console.log('e', e)
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            this.paginationInfo.currentPage = 1
            this.formData.keyword = searchKey
            this.getTableData()
        },
        onAdvanceSearch () {
            advanceSearch().then(res => {
                alert(JSON.stringify(res))
            })
        },
        goList () {
            this.viewList = true
        },
        handleCurrentChange (selection) {
            console.log('selection: ', selection)
            this.currentRow = selection
        },
        onCancel () {
            this.viewList = true
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
        goCategoryManage () {
            this.$router.push('/categoryManage')
        },
        onSave () {
            if(this.viewList === 'edit') {
                updateManagementUnit(this.formDataDetail).then(()=>{
                    this.clientPop('suc', '保存成功', ()=>{ this.viewList = true;this.paginationInfo.currentPage = 1;this.getTableData() })
                })
            }
        },
        changeEquip (val) {
            const arr = val ? [val] : []
            const that = this
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/hr/org/getOrgByUserId', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: arr, // 已选中id
                Title: '选择组织机构' // 标题
            }).then(val => {
                that.formDataDetail.managementUnit = val[0].orgName
                that.formDataDetail.managementUnitId = val[0].orgId
            }).catch(err=>{
                alert(err)
            })
        },
        setManage () {
            if(this.currentRow.length === 0) {
                this.clientPop('info', '请至少选择一条数据')
            }else{
                const arr = this.currentRow.map(x=>x.id)
                console.log('arr', arr)
                const that = this
                // 弹窗选择数据
                selectDataClient({
                    SelectServiceToken: '/hr/org/getOrgByUserId', // 客户端对应方法名
                    IsSingleMode: true, // 是否单选 true 单选 false 多选
                    SelectedIDs: [], // 已选中id
                    Title: '选择组织机构' // 标题
                }).then(val => {
                    const obj = {
                        orgId: val[0].orgId,
                        orgName: val[0].orgName,
                        basicManagementUnits: arr
                    }
                    setManagementUnit(obj).then(()=>{
                        that.clientPop('suc', '保存成功', ()=>{ this.viewList = true;this.paginationInfo.currentPage = 1;this.getTableData() })
                    })
                }).catch(err=>{
                    alert(err)
                })
            }
        }
    }
}
</script>

<style lang="scss" scoped>
</style>
